package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper orderMapper;
    /**
     * 定时处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeoutOrders(){
        log.info("处理支付超时订单:{}",new Date());
        LocalDateTime time=LocalDateTime.now().plusMinutes(-15);
        QueryWrapper<Orders> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("status", Orders.TO_BE_CONFIRMED)
                .le("order_time",time);
        List<Orders> ordersList = orderMapper.selectList(queryWrapper);
        if(ordersList != null){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.updateById(orders);
            });
        }

    }
    /**
     * 定时处理处于派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveredOrder(){
        log.info("处理派送订单:{}",new Date());
        LocalDateTime time=LocalDateTime.now().plusMinutes(-60);
        QueryWrapper<Orders> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("status", Orders.DELIVERY_IN_PROGRESS)
                .le("order_time",time);
        List<Orders> ordersList = orderMapper.selectList(queryWrapper);
        if(ordersList != null){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.updateById(orders);
            });
        }

    }


}
